/*********************
创建考核
* */
<template>
  <basic-container>
    <el-row>
      <targetExaminHead :sign="{ a: true, b: false, c: false,d: false,e: false}" />
    </el-row>
    <el-row style="margin:25px 0 0 0 ;">
      <div :height="searchheight">
        <span style="float:right;margin-top: -30px;cursor: pointer;" @click="searchchangeadvanced">
          {{ searchadvanced ? "查询条件收起" : "查询条件展开" }}
          <i
            :class="searchadvanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
          />
        </span>
        <div v-show="searchadvanced">
          <el-form :inline="true" :model="searchForm" class="form-inline">
            <el-form-item label="考核对象">
              <el-input v-model="searchForm.assessRealName" placeholder="考核对象" :clearable="true"></el-input>
            </el-form-item>
            <el-form-item label="考核名称">
              <el-input v-model="searchForm.name" placeholder="考核名称" :clearable="true"></el-input>
            </el-form-item>
            <el-form-item label="考核周期">
              <selectSearch @getDataByPerid="getDataByPerid"></selectSearch>
            </el-form-item>
            <el-form-item>
              <el-button
                icon="el-icon-search"
                type="primary"
                class="marginLeft"
                @click="getDataList(1)"
              >检索</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-row>
    <el-row>
      <div style="height: 50px; border-bottom: 1px solid #b0bde2">
        <el-tooltip
          class="item"
          effect="dark"
          :content="choosePerOrDept==0?'人员考核新增':'机构考核新增'"
          placement="top"
        >
          <el-button
            icon="el-icon-plus"
            type="primary"
            circle
            @click="choosePerOrDept==0?addPersonExam():addDeptExam()"
          ></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
          <el-button type="danger" icon="el-icon-delete" circle @click="deleteData"></el-button>
        </el-tooltip>
        <div class="pull-right">
          <el-button plain type="primary" @click="planPush">拟定推送</el-button>
          <el-button plain type="primary" @click="planPushSelf">拟定推送本人</el-button>
          <el-button plain type="primary" @click="download">指标跟踪导出</el-button>
        </div>
      </div>
      <div style="margin:20px 0 0 0 ">
        <span>指标考核&nbsp;&nbsp;</span>
        <el-radio-group v-model="choosePerOrDept" @change="choosePerOrDeptChange">
          <el-radio :label="0">人员</el-radio>
          <el-radio :label="1">机构</el-radio>
        </el-radio-group>
      </div>
    </el-row>
    <el-row>
      <el-table
        style="width: 100%;margin-top:20px"
        :data="dataList"
        border
        stripe
        header-align="center"
        v-if="rednermsg"
        v-loading="dataListLoading"
        @selection-change="handleSelectionChange"
        @cell-click="unfoldBtn"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" header-align="center" align="center" label="序号" width="55"></el-table-column>
        <el-table-column prop="assessUserName" align="center" label="员工编号" show-overflow-tooltip v-if="!choosePerOrDept"></el-table-column>
        <el-table-column prop="assessTarget" align="center" label="考核对象" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="scope.row.state==0">
              <span
                v-if="scope.row.type==0"
                @click="editRow(scope.row ,'edit')"
                style="color:rgb(14, 37, 140);cursor:pointer"
              >{{scope.row.assessRealName}}</span>
              <span
                v-else
                @click="editRow(scope.row ,'edit')"
                style="color:rgb(14, 37, 140);cursor:pointer"
              >{{scope.row.assessDeptName}}</span>
            </span>
            <span v-else>
              <span
                style="color:rgb(14, 37, 140);cursor:pointer"
                @click="viewRow(scope.row ,'view')"
                v-if="scope.row.type==0"
              >{{scope.row.assessRealName}}</span>
              <span
                style="color:rgb(14, 37, 140);cursor:pointer"
                @click="viewRow(scope.row ,'view')"
                v-else
              >{{scope.row.assessDeptName}}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="assessDeptName" align="center" label="部门" show-overflow-tooltip  v-if="!choosePerOrDept"></el-table-column>
        <el-table-column prop="itemNum" align="center" label="指标数量" show-overflow-tooltip height>
          <template slot-scope="scope">
            <div v-if="scope.row.zbnum != 0">
              <el-badge
                is-dot
                class="itembadge"
              >
                <el-popover placement="top" width="400" trigger="hover">
                  <el-table :data="scope.row.zbdata" max-height="360" size="small" >
                    <el-table-column width="180" property="sqzb" align="center" :label="'上期指标('+scope.row.sqzbnum+')'" show-overflow-tooltip></el-table-column>
                    <el-table-column width="180" property="bqzb" align="center" :label="'本期指标('+scope.row.bqzbnum+')'" show-overflow-tooltip></el-table-column>
                  </el-table>

                 <!-- <el-table :data="scope.row.sqzb" max-height="360" size="small" >
                    <el-table-column width="360" property="name" align="center" :label="'上期指标('+scope.row.sqzbnum+')'" show-overflow-tooltip></el-table-column>
                  </el-table>
                  <el-table :data="scope.row.bqzb" max-height="360" size="small" >
                    <el-table-column width="360" property="name" align="center" :label="'本期指标('+scope.row.bqzbnum+')'" show-overflow-tooltip></el-table-column>
                  </el-table>-->

               <!--   <div style="align-content: center;width:400px;height: auto;">
                    <div style="float: left;border: 0px solid rgb(176, 189, 226);width:46%;height:99%;margin-right: 2%;align-content: center;">
                      <div style="width:100%;height: 45px;line-height:45px;text-align: center;background-color: #b0bde2;color:black">上期指标({{scope.row.sqzbnum}})</div>
                      <div  style="width:100%;">
                        <ul  v-for="item in scope.row.sqzb"
                             :key="item.name"
                             :label="item.name">
                          <li>{{item.name}}</li>
                        </ul>
                      </div>
                    </div>
                    <div style="float: left;border: 0px solid rgb(176, 189, 226);width:46%;height:99%;align-content: center;">
                      <div style="width:100%;height: 45px;line-height:45px;text-align: center;background-color: #b0bde2;color:black">本期指标({{scope.row.bqzbnum}})</div>
                      <div  style="width:100%;">
                        <ul  v-for="item in scope.row.bqzb"
                             :key="item.name"
                             :label="item.name">
                          <li>{{item.name}}</li>
                        </ul>
                      </div>
                    </div>

                  </div>-->
                  <span slot="reference">{{ scope.row.itemNum }}&nbsp;</span>

                </el-popover>
              </el-badge>
            </div>
            <div v-else>
              <span>{{ scope.row.itemNum }}&nbsp;</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" align="center" label="考核名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="period" align="center" label="考核周期" show-overflow-tooltip></el-table-column>
       <!-- <el-table-column prop="weight" align="center" label="权重" show-overflow-tooltip>
          <template slot-scope="scope">
            <span :class="scope.row.weight==100?'weightColor':'weightRed'">{{scope.row.weight}}</span>
          </template>
        </el-table-column>-->
        <el-table-column
          prop="state"
          align="center"
          label="指标审核状态"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-popover placement="top" width="240" trigger="hover">
              <p></p>
              <div
                v-for="(item, index) in cutout(
                      scope.row.itemStr
                    )"
                :key="index"
              >
                <el-badge
                  v-if="scope.row.state != '0'"
                  :value="item.split('-')[1]"
                  :max="9"
                  class="itembadge"
                >
                      <span
                        v-if="item.indexOf('已完成') != -1"
                        style="color: #0bbf4a"
                      >{{ item.split("-")[0] }}</span
                      >
                  <span
                    v-else-if="item.indexOf('未完成') != -1"
                    style="color: red"
                  >{{ item.split("-")[0] }}</span
                  >
                  <span v-else>{{ item.split("-")[0] }}</span>
                </el-badge>
                <span v-else>{{ item.split("-")[0] }}</span>
              </div>
              <div slot="reference" class="name-wrapper">
                <span v-if="scope.row.state == 0">未提交</span>
                <span v-else-if="scope.row.state == 1"
                >拟定中</span
                >
                <span v-else-if="'2,3,4'.includes(scope.row.state)"
                >拟定审核中</span
                >
                <span v-else-if="scope.row.state == 5"
                >拟定已审核</span
                >
                <span v-else-if="scope.row.state == 6"
                >结果填报中</span
                >
                <span v-else-if="'7,8,9'.includes(scope.row.state)"
                >填报评审中</span
                >
                <span v-else-if="scope.row.state == 10"
                >确认中</span
                >
                <span v-else-if="scope.row.state == 11"
                >已结束</span
                >
              </div>
            </el-popover>
          </template>

        </el-table-column>
        <el-table-column prop="state" align="center" label="状态" show-overflow-tooltip>
          <template slot-scope="scope">
            <div>
              <el-popover placement="top" width="660" trigger="hover">
                <el-table :data="scope.row.gridData" max-height="400">
                  <el-table-column width="260" property="NAME_" label="任务名称" show-overflow-tooltip></el-table-column>
                  <el-table-column width="120" property="ry_name" label="处理人" show-overflow-tooltip></el-table-column>
                  <el-table-column
                    width="120"
                    property="START_TIME_"
                    label="开始时间"
                    show-overflow-tooltip
                  ></el-table-column>
                  <el-table-column
                    width="120"
                    property="END_TIME_"
                    label="结束时间"
                    show-overflow-tooltip
                  ></el-table-column>
                </el-table>
                <span slot="reference">{{scope.row.state | transTargetState}}</span>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="showMessage(scope.row.processId,scope.row)"
                >流程跟踪</el-button>
              </el-popover>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <div class="avue-crud__pagination">
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageData.pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageData.pageSize"
          :total="pageData.totalPage"
          background
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
    </el-row>
    <personExamine
      v-if="personVisible"
      ref="personNode"
      @closeDialog="closeDialog"
      @refesData="getDataList"
    />
    <personExamineView
      v-if="personViewVisible"
      ref="personViewNode"
      @closeDialog="closeViewDialog"
      @refesData="getDataList"
    />
    <departmentExamine
      v-if="deptVisible"
      ref="deptNode"
      @closeDialog="closeDialog1"
      @refesData="getDataList"
    />
    <departmentExamineView
      v-if="deptViewVisible"
      ref="deptViewNode"
      @closeDialog="closeDeptViewDialog"
      @refesData="getDataList"
    />

    <processTracking ref="processTracking" @processTrackingChildren="getDataList"></processTracking>
    <UserCommonSelect
      v-if="usercomment"
      ref="usercomment"
      @refreshDataList="getDataList"
      @submitfy="submitfy"
    ></UserCommonSelect>
    <el-dialog :visible.sync="palnSubVisible" append-to-body title="拟定推送">
      <p style="text-align:center">是否还需要选择其他数据填报人员</p>
      <span slot="footer" class="dialog-footer">
        <el-button plain type="primary" @click="confirmNeed">是</el-button>
        <el-button plain @click="cancelNeed">否</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import targetExaminHead from "@/views/dailyExamine/components/targetExaminHead"; //转态头
import personExamine from "./personExamine"; //人员考核组件
import personExamineView from "./personExamineView"; //人员考核组件
import departmentExamine from "./departmentExamine"; //机构考核组件
import departmentExamineView from "./departmentExamineView"; //机构考核组件

// import processTracking from "@/views/dailyExamine/components/targetProcessTracking"; //流程组件
import processTracking from "@/views/dailyExamine/components/zbProcessTracking"; //流程组件
import UserCommonSelect from "./formulateDialog2";
import selectSearch from "@/views/dailyExamine/components/select-search.vue"; //流程组件

import {
  examineList,
  defaultList,
  proposedPush,
  deleteExamin,
  pushbr,
  noKhzqList,
  examinDetail,targetTrackExportExcel} from "@/api/dailyExamine/targetExamine/createAssessment"; //接口api
export default {
  data() {
    return {
      deptViewVisible: false,
      personViewVisible: false,
      palnSubVisible: false,
      jsonData: [],
      ids: [],
      usercomment: false,
      choosePerOrDept: 0, //选择的是人员还是机构
      deptVisible: false, //机构考核组件显隐
      personVisible: false, //人员考核组件显隐
      searchheight: "0", //搜索组件的高度
      searchadvanced: true, //搜索的显隐
      searchForm: {}, //搜索对象
      dataListLoading: false, //表格是否加载
      dataList: [], //表格数组
      multipleSelection: [], //勾选数据
      pageData: {
        //分页对象
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0
      },
      headData: {} ,//总部启动的考核数据对象
      rednermsg:true,
      khzqFlag:true,
    };
  },
  components: {
    departmentExamineView,
    personExamineView,
    targetExaminHead, //状态头
    personExamine, //人员考核组件
    departmentExamine, //机构考核组件
    processTracking, //流程组件
    UserCommonSelect,
    selectSearch
  },
  created() {
    this.getDataList();
    this.getHeadList();
  },
  methods: {
    // 不需要其他填报人员
    cancelNeed() {},
    // 需要其他填报人员
    confirmNeed() {
      this.usercomment = true;
      this.jsonData = JSON.stringify(["1331", "1330"]);
      this.$nextTick(() => {
        this.$refs.usercomment.init("12", "ndts", this.jsonData, "ndts");
      });
    },
    submitfy(data) {
      this.palnSubVisible = false;
      this.usercomment = false;

      let ids = this.multipleSelection.map(it => {
        return it.id;
      });
      let otherId = data.tableDataUser.map(it => {
        return it.userId;
      });

        let orgId = data.selectorgdata.map(it => {
            return it.userId;
        });
      proposedPush(ids.toString(), otherId.toString(),orgId.toString())
        .then(r => {
          if (r.data.code == 0) {
            this.$message.success("推送成功");
            this.getDataList();
          } else {
            this.$message.error(r.data.msg);
            this.getDataList();
          }
        })
        .catch(err => {
          this.getDataList();
        });
    },
    // 编辑
    async  editRow(row, type) {
          if(!this.khzqFlag){
              await noKhzqList(row.assessId)
                  .then(r => {
                      console.log(r)
                      if (r.data.code == 0) {
                          this.headData = r.data;
                      } else {
                          this.headData = {};
                      }
                  })
          }
      if (row.type == 0) {
        this.personVisible = true;
        this.$nextTick(() => {
          this.$refs.personNode.init(this.headData, row, type);
        });
      } else {
        this.deptVisible = true;
        this.$nextTick(() => {
          this.$refs.deptNode.init(this.headData, row, type);
        });
      }
    },
    async  viewRow(row, type) {
          if(!this.khzqFlag){
              await noKhzqList(row.assessId)
                  .then(r => {
                      console.log(r)
                      if (r.data.code == 0) {
                          this.headData = r.data;
                      } else {
                          this.headData = {};
                      }
                  })
          }
      if (row.type == 0) {
        this.personViewVisible = true;
        this.$nextTick(() => {
          this.$refs.personViewNode.init(this.headData, row, type);
        });
      } else {
        this.deptViewVisible = true;
        this.$nextTick(() => {
          this.$refs.deptViewNode.init(this.headData, row, type);
        });
      }
    },
    showMessage(proId, row) {
      this.$refs.processTracking.init(proId);
    },
    //  人员or机构选择改变
    choosePerOrDeptChange(val) {
      this.searchForm = {};
      this.dataList = [];
      this.getDataList();
    },
    //考核对象展示
    unfoldBtn(row) {
      row.rowshows = !row.rowshows;
      this.rednermsg = false;
      this.$nextTick(() => {
        this.rednermsg = true;
      });
    },
    //数组
    cutout(cellValue) {
      if (cellValue) {
        var c = cellValue.split(",");
        if (c.size < 1) {
          c.push("-");
          c.push("-");
        } else if (c.size < 2) {
          c.push("-");
        }
        return c;
      }
    },
    // 查询总部启动的考核
    getHeadList() {
      defaultList()
        .then(r => {
          if (r.data.code == 0) {
            this.headData = r.data;
          } else {
            this.headData = {};
          }
        })
        .catch(err => {
            this.khzqFlag = false;
        });
    },
    // 拟定推送
    planPush() {
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请先选择要推送的数据");
      } else {

          let flag = this.multipleSelection.every( it=> {
              return it.state == 0
          })

          if(!flag){
              this.$message.warning("只有创建中的数据才可推送");
              return ;
          }
           let zbslFalg = this.multipleSelection.some( it=> {
                      return it.itemNum == 0
          })

        //推送操作
        this.$confirm("是否还需要选择其他数据填报人员", "提示", {
            distinguishCancelAndClose:true,
            confirmButtonText: "是",
            cancelButtonText: "否",
            closeOnClickModal: false,
            type: "warning"
        })
          .then(result => {
            // 选择其他填报数据人员
            this.usercomment = true;
            this.jsonData = JSON.stringify([]);
            this.$nextTick(() => {
              this.$refs.usercomment.init("12", "ndts", this.jsonData, "ndts");
            });
          })
          .catch(err => {
              //判断是 cancel (自定义的取消) 还是 close （关闭弹窗）
              if(err === 'cancel'){
                  //指标数量为0
                  if(zbslFalg){
                      // 不执行任何操作
                      this.$message.warning("拟定指标推送人为空，请选择拟定指标负责人推送。");
                  }else{
                      // 不选择其他数据填报人员
                      let ids = this.multipleSelection.map(it => {
                          return it.id;
                      });
                      proposedPush(ids.toString())
                          .then(r => {
                              if (r.data.code == 0) {
                                  this.$message.success("推送成功");
                                  this.getDataList();
                              } else {
                                  this.$message.error(r.data.msg);
                                  this.getDataList();
                              }
                          })
                          .catch(err => {
                              this.getDataList();
                          });
                  }
              }
              if(err === 'close'){
                  console.log(err);
              }


          });
      }
    },
    // 拟定推送自己
    planPushSelf() {
        if (this.multipleSelection.length == 0) {
            this.$message.warning("请先选择要推送的数据");
        } else {

            let flag = this.multipleSelection.every( it=> {
                return it.state == 0
            })

            if(!flag){
                this.$message.warning("只有创建中的数据才可推送");
                return ;
            }
          /*  let zbslFalg = this.multipleSelection.every( it=> {
                return it.itemNum == 0
            })
            if(!zbslFalg){
                this.$message.warning("只有指标为0的数据才能推送自己");
                return ;
            }*/
            //推送操作
            this.$confirm("是否要将数据推送给自己", "提示", {
                distinguishCancelAndClose:true,
                confirmButtonText: "是",
                cancelButtonText: "否",
                closeOnClickModal: false,
                type: "warning"
            })
                .then(result => {

                    let ids = this.multipleSelection.map(it => {
                        return it.id;
                    });
                    pushbr(ids.toString())
                        .then(r => {
                            console.log(r)
                            if(!r.data.data){
                                this.$message.error("不能跳过指标拟定环节!");
                            }else{
                                if (r.data.code == 0) {
                                    this.$message.success("推送成功");
                                    this.getDataList();
                                } else {
                                    this.$message.error(r.data.msg);
                                    that.getDataList();
                                }
                            }

                        })
                        .catch(err => {});
                })

                .catch(err => {
                    //判断是 cancel (自定义的取消) 还是 close （关闭弹窗）
                    if(err === 'cancel'){
                        console.log(err);
                    }
                    if(err === 'close'){
                        console.log(err);
                    }

                });
        }
    },
    // 删除数据
    deleteData() {
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请先选择要删除的数据");
      } else {
        //删除操作
        let ids = this.multipleSelection.map(it => {
          return it.id;
        });
        let that = this;
        this.$confirm("确定要删除勾选的数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(_ => {
            deleteExamin(ids.toString())
              .then(r => {
                if (r.data.code == 0) {
                  this.$message.success("删除成功");
                  this.getDataList();
                } else {
                  this.$message.error(r.data.msg);
                  that.getDataList();
                }
              })
              .catch(err => {});
          })
          .catch(_ => {
            that.getDataList();
          });
      }
    },
    // 新增机构考核
    addDeptExam() {
      this.deptVisible = true;
      this.$nextTick(() => {
        this.$refs.deptNode.init(this.headData);
      });
    },
    //   新增人员考核
    addPersonExam() {
      this.personVisible = true;
      this.$nextTick(() => {
        this.$refs.personNode.init(this.headData);
      });
    },
    // 查询条件的展开关闭
    searchchangeadvanced() {
      this.searchadvanced = !this.searchadvanced;
      if (this.searchadvanced) {
        this.searchheight = "auto";
      }
    },
    // 查询列表
    getDataList() {
      ////
      this.dataListLoading = true ;
      examineList(
        Object.assign(
          {
            current: this.pageData.pageIndex,
            size: this.pageData.pageSize,
            type: this.choosePerOrDept
          },
          this.searchForm
        ),
        0
      )
        .then(r => {
          if (r.data.code == 0) {
            this.dataListLoading = false ;
            this.dataList = r.data.data.records.map(it => {
              return it;
            });
            this.pageData.totalPage = r.data.data.total;
          }
        })
        .catch(err => {});
    },
    // 编辑事件
    EditEvt(data) {
      // 这里回显被考核人或者机构 还有指标的回显有问题
      this.personVisible = true;
      // 详情查询
      examinDetail(data.id)
        .then(r => {})
        .catch(err => {});
      if (data) {
        this.$nextTick(() => {
          this.$refs.personNode.init({ data });
        });
      } else {
        this.$nextTick(() => {
          this.$refs.personNode.init();
        });
      }
    },
    // 勾选数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 条数变化
    sizeChangeHandle(val) {
      this.pageData.pageSize = val;
      this.getDataList();
    },
    // 页码分页变化
    currentChangeHandle(val) {
      this.pageData.pageIndex = val;
      this.getDataList();
    },
    // 关闭人员考核新增弹窗
    closeDialog() {
      this.personVisible = false;
      this.getDataList();
    },
    closeViewDialog() {
      this.personViewVisible = false;
      this.getDataList();
    },

    // 关闭机构考核新增弹窗
    closeDialog1() {
      this.deptVisible = false;
      this.getDataList();
    },

    closeDeptViewDialog() {
      this.deptViewNode = false;
      this.getDataList();
    },
      download(){
          var data = this.multipleSelection;
          if (data.length == 0) {
              this.$message.closeAll();
              this.$message.warning("请选择一个工作！");
              return;
          }
          var filename = "指标跟踪导出"+ ".xlsx";
          var ids = [];
          for (var i = 0; i < data.length; i++) {
              ids.push(data[i].id);
          }
          targetTrackExportExcel({
              ids: ids
          }).then((response) => {
              this.$message.closeAll();
              this.$message.success("导出成功!");
              let url = window.URL.createObjectURL(new Blob([response.data]));
              let link = document.createElement("a");
              link.style.display = "none";
              link.href = url;
              link.setAttribute("download", filename);
              document.body.appendChild(link);
              link.click();
          });
      },
      //选择周期执行搜索功能
      getDataByPerid(period){
          this.searchForm.period = period ;
          this.getDataList() ;
      }
  }
};
</script>

<style lang="scss" scoped>
  .itembadge {
    margin-top: 10px;
    margin-right: 0px;
  }
::v-deep .el-select .el-select__tags {
  overflow: auto !important;
}
::v-deep.el-tag.el-tag--info {
  margin: 5px;
  border: 1px solid green;
}
::v-deep.el-divider {
  background-color: #b0bde2 !important;
}
.weightRed {
  color: rgba(255, 0, 0, 0.726);
}
</style>
